package com.china08.yxyapi.service.yxweike.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.china08.yxyapi.entity.db.lessons.YxyLessonsSynchroLesson;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsSynchroLessonChapter;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsSynchroLessonItem;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.model.resource.ChapterModel;
import com.china08.yxyapi.model.resource.Item;
import com.china08.yxyapi.model.resource.ItemModel;
import com.china08.yxyapi.repository.db.YxyLessonsSynchroLessonChapterRepository;
import com.china08.yxyapi.repository.db.YxyLessonsSynchroLessonItemRepository;
import com.china08.yxyapi.repository.db.YxyLessonsSynchroLessonRepository;
import com.china08.yxyapi.service.yxweike.YxyLessonsSynLessonService;
import com.china08.yxyapi.service.yxweike.YxyResWeikeService;

@Service
public class YxyLessonsSynLessonServiceImpl implements YxyLessonsSynLessonService {

    @Autowired
    private YxyLessonsSynchroLessonItemRepository yxyLessonsSynchroLessonItemRepository;

    @Autowired
    private YxyLessonsSynchroLessonChapterRepository yxyLessonsSynchroLessonChapterRepository;

    @Autowired
    private YxyLessonsSynchroLessonRepository yxyLessonsSynchroLessonRepository;

    @Autowired
    private YxyResWeikeService yxyResWeikeService;

    @Override
    public void chapterAddItem(String chapterId, List<ItemModel> itemModels) {

        //
        YxyLessonsSynchroLessonChapter chapter = yxyLessonsSynchroLessonChapterRepository.findOne(chapterId);
        Assert.notNull(chapter, "章节未找到");

        YxyLessonsSynchroLesson lesson = yxyLessonsSynchroLessonRepository.findById(chapter.getLessonId());
        Assert.notNull(lesson, "课程找不到了");
        // if (lesson.getIsVisible() != 0) {
        // lesson.setIsVisible(0);
        // lesson.setDownDate(new Date());
        // yxyLessonsSynchroLessonRepository.save(lesson);
        // }
        //
        String lessonId = chapter.getLessonId();

        // ##
        List<String> weikeIds = itemModels.stream().map(x -> x.weikeId).collect(Collectors.toList());
        Assert.isTrue(weikeIds.size() > 0, "请选择微课");

        // ##
        List<ElasticYxyResResource> elasticYxyResResources = yxyResWeikeService.findByIdIn(weikeIds);
        Assert.isTrue(elasticYxyResResources.size() > 0, "微课找不到了");

        //
        Integer check = yxyLessonsSynchroLessonItemRepository.countByWeikeIdInAndLessonIdAndStatusNot(weikeIds,
                lessonId, -1);
        Assert.isTrue(check == 0, "选中的微课已存在该课程");

        Integer order = 0;
        // ##
        for (ElasticYxyResResource elasticYxyResResource : elasticYxyResResources) {
            String weikeId = elasticYxyResResource.getId();
            //
            Integer chapterItemMaxOrderNum = yxyLessonsSynchroLessonItemRepository.maxByChapterIdAndDelNot(chapterId);
            if (chapterItemMaxOrderNum == null || chapterItemMaxOrderNum == 0) {
                YxyLessonsSynchroLessonChapter minTop1Chapter = yxyLessonsSynchroLessonChapterRepository
                        .findTop1ByLessonIdAndOrderNumLessThanOrderByOrderNumDesc(chapter.getLessonId(),
                                chapter.getOrderNum());
                if (minTop1Chapter != null) {
                    YxyLessonsSynchroLessonItem minChapterMaxItem = yxyLessonsSynchroLessonItemRepository
                            .findTop1ByChapterIdAndStatusNotOrderByOrderNumDesc(minTop1Chapter.getId(), -1);
                    if (minChapterMaxItem != null) {
                        chapterItemMaxOrderNum = minChapterMaxItem.getOrderNum();
                    }
                }
            }
            chapterItemMaxOrderNum = chapterItemMaxOrderNum == null ? 20 : chapterItemMaxOrderNum + 1;
            //
            YxyLessonsSynchroLessonItem item = new YxyLessonsSynchroLessonItem();
            item.setChapterId(chapterId);
            item.setTitle(elasticYxyResResource.getTitle());
            item.setIntro(elasticYxyResResource.getIntro());
            item.setStatus(2);
            item.setWeikeId(weikeId);
            item.setOrderNum(chapterItemMaxOrderNum);
            item.setLessonId(lessonId);
            //
            Optional<ItemModel> itemModel = itemModels.stream()
                    .filter(x -> StringUtils.equalsIgnoreCase(weikeId, x.weikeId)).findAny();
            item.setPreview(itemModel.get().preview);
            //
            yxyLessonsSynchroLessonItemRepository.save(item);
            order++;

        }
        chapterByChapterIdOrderItems(chapterId, order);
        // 更新课时数量
        updLessonItems(lesson);
    }

    public void updLessonItems(YxyLessonsSynchroLesson lesson) {
        String lessonId = lesson.getId();
        lesson.setCount(yxyLessonsSynchroLessonItemRepository.countByLessonIdAndStatusNot(lesson.getId(), -1));

        List<YxyLessonsSynchroLessonItem> items = yxyLessonsSynchroLessonItemRepository
                .findByLessonIdAndStatusNot(lessonId, -1);
        List<String> weikeIds = items.stream().map(x -> x.getWeikeId()).collect(Collectors.toList());
        if (weikeIds.size() > 0) {
            List<ElasticYxyResResource> elasticYxyResResources = yxyResWeikeService.findByIdIn(weikeIds);
            Integer duration = 0;
            for (ElasticYxyResResource elasticYxyResResource : elasticYxyResResources) {
                duration = duration + elasticYxyResResource.getDuration();
            }
            lesson.setDuration(duration);
        }
        // if (lesson.getIsVisible() == 1) {
        // lesson.setIsVisible(0);
        // lesson.setDownDate(new Date());
        // lesson.setDownReason("修改课程");
        // lesson.setDownType("其他");
        // }
        yxyLessonsSynchroLessonRepository.save(lesson);
    }

    @Override
    public void chapterByChapterIdOrderItems(String chapterId, Integer orderNum) {
        //
        YxyLessonsSynchroLessonChapter chapter = yxyLessonsSynchroLessonChapterRepository.findOne(chapterId);
        Assert.notNull(chapter, "章节未找到");

        //
        String lessonId = chapter.getLessonId();
        Integer chapterOrder = chapter.getOrderNum();

        //
        List<YxyLessonsSynchroLessonChapter> chapters = yxyLessonsSynchroLessonChapterRepository
                .findByLessonIdAndOrderNumGreaterThan(lessonId, chapterOrder);
        for (YxyLessonsSynchroLessonChapter yxyLessonsSynchroLessonChapter : chapters) {
            //
            List<YxyLessonsSynchroLessonItem> items = yxyLessonsSynchroLessonItemRepository
                    .findByChapterIdAndStatusNot(yxyLessonsSynchroLessonChapter.getId(), -1);
            //
            for (YxyLessonsSynchroLessonItem yxyLessonsSynchroLessonItem : items) {
                yxyLessonsSynchroLessonItem.setOrderNum(yxyLessonsSynchroLessonItem.getOrderNum() + orderNum);
                yxyLessonsSynchroLessonItemRepository.save(yxyLessonsSynchroLessonItem);
            }
        }
    }

    @Override
    public void delChapter(String chapterId) {

        Integer check = yxyLessonsSynchroLessonItemRepository.countByChapterIdAndStatusNot(chapterId, -1);
        Assert.isTrue(check == 0, "该章节下有课时禁止删除");

        //
        YxyLessonsSynchroLessonChapter chapter = yxyLessonsSynchroLessonChapterRepository.findOne(chapterId);
        Assert.notNull(chapter, "章节未找到");
        //
        YxyLessonsSynchroLesson lesson = yxyLessonsSynchroLessonRepository.findById(chapter.getLessonId());
        Assert.notNull(lesson, "课程找不到了");
        // if (lesson.getIsVisible() != 0) {
        // lesson.setIsVisible(0);
        // lesson.setDownDate(new Date());
        // lesson.setDownReason("修改课程");
        // lesson.setDownType("其他");
        // yxyLessonsSynchroLessonRepository.save(lesson);
        // }

        //
        Integer chapterItemCount = yxyLessonsSynchroLessonItemRepository.countByChapterIdAndStatusNot(chapterId, -1);
        chapterByChapterIdOrderItems(chapterId, -chapterItemCount);
        //
        List<YxyLessonsSynchroLessonItem> items = yxyLessonsSynchroLessonItemRepository
                .findByChapterIdAndStatusNot(chapterId, -1);
        for (YxyLessonsSynchroLessonItem yxyLessonsSynchroLessonItem : items) {
            yxyLessonsSynchroLessonItem.setStatus(-1);
            yxyLessonsSynchroLessonItemRepository.save(yxyLessonsSynchroLessonItem);
        }
        chapterOrder(chapterId);
        yxyLessonsSynchroLessonChapterRepository.delete(chapter);
        //

    }

    @Override
    public void chapterDelItem(String chapterId, String itemId) {

        //
        YxyLessonsSynchroLessonChapter chapter = yxyLessonsSynchroLessonChapterRepository.findOne(chapterId);
        Assert.notNull(chapter, "章节未找到");
        String lessonId = chapter.getLessonId();

        YxyLessonsSynchroLesson lesson = yxyLessonsSynchroLessonRepository.findById(chapter.getLessonId());
        Assert.notNull(lesson, "课程找不到了");
        // if (lesson.getIsVisible() != 0) {
        // lesson.setIsVisible(0);
        // lesson.setDownDate(new Date());
        // lesson.setDownReason("修改课程");
        // lesson.setDownType("其他");
        // yxyLessonsSynchroLessonRepository.save(lesson);
        // }

        //
        YxyLessonsSynchroLessonItem item = yxyLessonsSynchroLessonItemRepository.findById(itemId);
        Assert.notNull(item, "课时未找到");
        Integer itemOrderNum = item.getOrderNum();
        //
        List<YxyLessonsSynchroLessonItem> items = yxyLessonsSynchroLessonItemRepository
                .findByLessonIdAndChapterIdAndOrderNumGreaterThanAndStatusNot(lessonId, chapterId, itemOrderNum, -1);
        for (YxyLessonsSynchroLessonItem yxyLessonsSynchroLessonItem : items) {
            yxyLessonsSynchroLessonItem.setOrderNum(yxyLessonsSynchroLessonItem.getOrderNum() - 1);
            yxyLessonsSynchroLessonItemRepository.save(yxyLessonsSynchroLessonItem);
        }
        //
        chapterByChapterIdOrderItems(chapterId, -1);

        //
        item.setStatus(-1);
        yxyLessonsSynchroLessonItemRepository.save(item);
        // yxyLessonsSynchroLessonItemRepository.delete(item);
        // 更新课时数量
        updLessonItems(lesson);

    }

    @Override
    public void chapterOrder(String chapterId) {
        //
        YxyLessonsSynchroLessonChapter chapter = yxyLessonsSynchroLessonChapterRepository.findOne(chapterId);
        Assert.notNull(chapter, "章节未找到");

        //
        String lessonId = chapter.getLessonId();
        Integer chapterOrder = chapter.getOrderNum();

        List<YxyLessonsSynchroLessonChapter> chapters = yxyLessonsSynchroLessonChapterRepository
                .findByLessonIdAndOrderNumGreaterThan(lessonId, chapterOrder);

        for (YxyLessonsSynchroLessonChapter yxyLessonsSynchroLessonChapter : chapters) {
            yxyLessonsSynchroLessonChapter.setOrderNum(yxyLessonsSynchroLessonChapter.getOrderNum() - 1);
            yxyLessonsSynchroLessonChapterRepository.save(yxyLessonsSynchroLessonChapter);
        }

    }

    @Override
    public void chapterItemSort2(List<ChapterModel> chapterModels, String lessonId) {
        YxyLessonsSynchroLesson lesson = yxyLessonsSynchroLessonRepository.findById(lessonId);
        Assert.notNull(lesson, "课程找不到了");
        // if (lesson.getIsVisible() != 0) {
        // lesson.setIsVisible(0);
        // lesson.setDownDate(new Date());
        // lesson.setDownReason("修改课程");
        // lesson.setDownType("其他");
        // yxyLessonsSynchroLessonRepository.save(lesson);
        // }

        List<String> chapterIds = new ArrayList<String>();
        List<String> itemsIds = new ArrayList<String>();
        for (ChapterModel string : chapterModels) {
            chapterIds.add(string.chapterId);
            itemsIds.addAll(string.getItems().stream().map(x -> x.getId()).collect(Collectors.toList()));
        }
        // 计算数量课时 章节数量是否和数据库一样 5
        Integer countChapter = yxyLessonsSynchroLessonChapterRepository.countByLessonId(lessonId);
        Integer countChapter2 = yxyLessonsSynchroLessonChapterRepository.countByLessonIdAndIdIn(lessonId, chapterIds);
        Assert.isTrue(countChapter == countChapter2, "章节已变动请刷新页面");
        // 查看课时是否一样
        Integer countItem = yxyLessonsSynchroLessonItemRepository.countByLessonIdAndStatusNot(lessonId, -1);
        Integer countItem2 = yxyLessonsSynchroLessonItemRepository.countByLessonIdAndIdInAndStatusNot(lessonId,
                itemsIds, -1);
        Assert.isTrue(countItem == countItem2, "课时已变动");

        int orderNum = 20;
        for (ChapterModel chapterModel : chapterModels) {
            for (Item itm : chapterModel.getItems()) {
                YxyLessonsSynchroLessonItem yxyLessonsSynchroLessonItem = yxyLessonsSynchroLessonItemRepository
                        .findById(itm.getId());
                if (yxyLessonsSynchroLessonItem != null) {
                    yxyLessonsSynchroLessonItem.setOrderNum(orderNum);
                    yxyLessonsSynchroLessonItem.setStatus(2);
                    yxyLessonsSynchroLessonItem.setChapterId(chapterModel.chapterId);
                    yxyLessonsSynchroLessonItemRepository.save(yxyLessonsSynchroLessonItem);
                    orderNum++;
                }
            }
        }

    }

}
